﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace AutoInsurance
{
    public partial class newPolicy : System.Web.UI.Page
    {
        private Int32 id_client;
        public Int32 power;
        private int id_manager;
        //private Int32 agId;
        private String agId;
        private String vin_code;
        private Int32 i = 0;
        private String lab;
        private int role;
        private string name;
        private string surname;
        private string login;

        private string Сon = @"Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=AUTOINSURANCE;Integrated Security=True;Pooling=False";
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
            //берем id менеджера по логину в сессии
                SqlConnection connection = new SqlConnection(Сon);
                connection.Open();
                SqlCommand searchManager = new SqlCommand("select * from Manager where login=" + "'" + Session["login"] + "'" , connection);
                SqlDataReader id_m = searchManager.ExecuteReader();
                id_m.Read();
                id_manager = id_m.GetInt32(0);
                connection.Close();

                login = Convert.ToString(Session["login"]);
                role = Convert.ToInt32(Session["role"]);
                name = Convert.ToString(Session["name"]);
                surname = Convert.ToString(Session["surname"]);
                Label2.Text = Convert.ToString(id_manager);
                agId = Convert.ToString(Label2.Text);
                //agId = Label2.Text;
                DropDownList1.Items.Add(Label2.Text);
                Session.Remove("login");
                Session.Remove("role");
                Session.Remove("name");
                Session.Remove("surname");
                Session["login"] = login;
                Session["name"] = name;
                Session["surname"] = surname;
                Session["role"] = role;
                DropDownList1.SelectedIndex = 0;
                Label2.Text = DropDownList1.SelectedValue;
                //Label4.Text = Convert.ToString(id_manager);
            }
            catch (Exception ex)
            {
                Server.Transfer("Error.aspx?error=" + ex.Message);
            }
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

            TextBox1.Text = "";
            TextBox2.Text = "";
            TextBox4.Text = "";
            TextBox5.Text = "";
            TextBox12.Text = "";
            HyperLink1.Visible = false;
            Panel1.Visible = true;
            //Label1.Text = Convert.ToString(clId);
            Label3.Visible = false;
        }
        //добавляем новое авто
        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                vin_code = Convert.ToString(TextBox1.Text);
                Label6.Text = vin_code;
                //Panel1.Visible = true;
                Panel2.Visible = true;
                SqlConnection connection = new SqlConnection(Сon);
                connection.Open();
                try
                {
                    /*SqlCommand searchAuto = new SqlCommand("select vin_code from Auto where vin_code=" + "'" + vin_code + "'", connection);
                    SqlDataReader id_auto = searchAuto.ExecuteReader();
                    id_auto.Read();
                    String id_ex = id_auto.GetString(0);
                    if (id_ex == "")
                    {*/
                    id_client = Convert.ToInt32(GridView1.SelectedDataKey.Value);
                    power = Convert.ToInt32(TextBox5.Text);
                    SqlCommand сommand1 = new SqlCommand("insert into Auto (vin_code, id_client, mark, model, power)" +
                        "VALUES ('" + vin_code + "','" + id_client + "','" + TextBox2.Text + "','" + TextBox4.Text + "','" + power + "')", connection);
                    сommand1.ExecuteNonQuery();
                }

                    /*else
                    {
                        Label5.Text = "Ошибка при вставке данных: автомобиль с таким вин-кодом уже существует ";
                        Panel2.Visible = false;
                    }
            
                }*/
                catch (SqlException ex)
                {
                    Label3.Text = ("Ошибка при вставке данных: " + ex.Message);
                }
                connection.Close();
                Label4.Text = Convert.ToString(power);
                Label5.Visible = true;
            }
            catch (Exception ex)
            {
                Server.Transfer("Error.aspx?error=" + ex.Message);
            }
        }
        //добавляем новый полис
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                Boolean isopen;
                String type;
                //agId = Convert.ToInt32(DropDownList1.SelectedValue);
                if (RadioButtonList1.SelectedValue == "Без ограничений")
                {
                    isopen = true;
                }
                else
                {
                    isopen = false;
                }

                if (RadioButtonList2.SelectedValue == "ОСАГО")
                {
                    type = "ОСАГО";
                }
                else
                {
                    type = "KACKO";
                }


                if (TextBox12.Text != null)
                {
                    SqlConnection connection = new SqlConnection(Сon);
                    connection.Open();

                    try
                    {
                        SqlCommand newPolicy = new SqlCommand("insert into Policy (vin_code, id_manager, overdate, isopen, type, totalsum, giveout)" +
                            "VALUES ('" + Label6.Text + "','" + id_manager + "','" + TextBox7.Text + "','" + isopen + "','" + type + "','" + TextBox12.Text + "','" + 0 + "')", connection);
                        newPolicy.ExecuteNonQuery();

                        Label3.Text = "Новый полис успешно добавлен!";
                    }
                    catch (SqlException ex)
                    {
                        Label3.Text = ("Ошибка при вставке данных: " + ex.Message);


                    }
                    connection.Close();
                    Panel2.Visible = true;

                    Label3.Visible = true;
                    /*TextBox1.Text = "";
                    TextBox2.Text = "";
                    TextBox3.Text = "";
                    TextBox4.Text = "";
                    TextBox5.Text = "";
                    TextBox7.Text = "";
                    TextBox12.Text = "";*/
                }
                else
                {
                    Label3.Text = "Рассчитайте стоимость полиса";
                }
            }
            catch (Exception ex)
            {
                Server.Transfer("Error.aspx?error=" + ex.Message);
            }
         }
        //считаем стоимость полиса
        protected void Button3_Click(object sender, EventArgs e)
        {
            try
            {
                double expfactor;
                double agefactor;
                double powerfactor;

                int n3 = Convert.ToInt32(Label4.Text);
                if (n3 < 50)
                {
                    powerfactor = 1;
                }
                else if (n3 > 50 && n3 <= 70)
                {
                    powerfactor = 2;
                }
                else if (n3 > 70 && n3 <= 100)
                {
                    powerfactor = 3;
                }
                else if (n3 > 100 && n3 <= 120)
                {
                    powerfactor = 4;
                }
                else if (n3 > 120 && n3 <= 150)
                {
                    powerfactor = 5;
                }
                else if (n3 > 150)
                {
                    powerfactor = 6;
                }
                else
                {
                    powerfactor = 0;
                }
                double openfactor;
                double typefactor;
                double factor;
                int n1 = Convert.ToInt32(TextBox3.Text);
                if (n1 <= 3)
                {
                    expfactor = 1.5;
                }
                else
                {
                    expfactor = 1;
                }

                if (ListBox2.SelectedValue == "2")
                {
                    agefactor = 1.5;
                }
                else
                {
                    agefactor = 1.18;
                }
               
               
                if (RadioButtonList1.SelectedValue == "Без ограничений")
                {
                    openfactor = 1.3;
                }
                else
                {
                    openfactor = 1.14;
                }

                if (ListBox1.SelectedValue == "Мотоциклы и мотороллеры")
                {
                    typefactor = 1;
                }
                else if (ListBox1.SelectedValue == "Легковые автомобили")
                {
                    typefactor = 1.2;
                }
                else
                {
                    typefactor = 1.4;
                }

                if (RadioButtonList2.SelectedValue == "ОСАГО")
                {
                    factor = 450;
                }
                else
                {
                    factor = 620;
                }
                double sum = factor * typefactor * openfactor * powerfactor * agefactor * expfactor;
                string s1 = Convert.ToString(sum);
                TextBox12.Text = s1;
                Button1.Visible = true;
            }
            catch (FormatException)
            {
                TextBox12.Text = "Ошибка! Неверный формат данных";
            }
            catch (Exception ex)
            {
                Server.Transfer("Error.aspx?error=" + ex.Message);
            }

        }
             
        }
    }
